<template>
  <div class="pk-upload">
    <div class="pk-upload-item" v-if="limit > list.length">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="/common/file/uploadFile"
        :auto-upload="true"
        :show-file-list="false"
        :limit="limit"
        :headers="headers"
        :on-success="onSuccess"
      >
        <template #trigger>
          <div class="pk-upload-add">
            <div><el-icon color="#999"><Plus /></el-icon></div>
            <div class="pk-upload-title">{{ title }}</div>
          </div>
        </template>
      </el-upload>
    </div>
    <div class="pk-upload-item" v-for="(item, index) in list" :key="index" :style="{background: 'url('+item.url+') center center no-repeat', backgroundSize: 'cover'}" @click="delItem(item, index)">
      <div class="pk-upload-closeIcon">
        <el-icon><DeleteFilled /></el-icon>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch,  } from 'vue'
import { Plus, DeleteFilled } from '@element-plus/icons-vue'
import { getToken, setKeyItem} from '@/utils/auth'
const emit = defineEmits(['upload'])
const props = defineProps({
  title:{
    type: String,
    default: '上传图片'
  },
  defaultList: {
    type: Array,
    default: () => []
  },
  limit: {
    type: Number,
    default: 1
  }
})

const headers = ref({
  Authorization: "Bearer " + getToken()

})

watch(() => props.defaultList, (newValue) => {
  if (newValue) {
    list.value = newValue

  }
})

const list = ref(props.defaultList)

const onSuccess = (e) => {
  list.value.push(e.resData)
  emit('upload', list.value)
}

const delItem = (e, index) => {
  list.value.splice(index, 1)
}
</script>

<style lang="scss">
.pk-upload{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  &-item{
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    border-radius: 8px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    margin-left: 12px;
    flex: 0 0 auto;
    position: relative;
  }
  &-closeIcon{
    position: absolute;
    top:0;
    right:0;
    width: 20px;
    height: 20px;
    background: #000;
    color: #fff;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  &-title{
    font-size: 12px;
    color: #999;
    margin-left: 4px;
  }
  &-add{
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    border-radius: 8px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
}
</style>